package com.xcw.config;

import com.xcw.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @Author bhx
 * @Date 2022/6/12 23:14
 * @Description TODO
 */
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    @Resource
    private RedisUtils redisUtils;

    @Value("${openlist.login}")
    private String url;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                String accessToken = request.getHeader("AccessToken");
                if (!StringUtils.isEmpty(accessToken) && !StringUtils.isEmpty(redisUtils.get(accessToken))) {
                    redisUtils.expire(accessToken, 30, TimeUnit.MINUTES);
                    return true;
                }
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return false;
            }
        }).excludePathPatterns(url, "/**");
    }
}
